package com.voicechat.firstmet.view.recyclerview.mo;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.bean.FristMetBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Lym on 2018/1/6.
 */

public class MoCardAdapter extends RecyclerView.Adapter implements View.OnClickListener {
    private Context context;
    private MoCardViewHolder holder;
    private List<FristMetBean.PageBean.ListBean> list;
    public ItemClick itemClick;
    private int position;
    private String TAG = "MoCardAdapter";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Bundle data = msg.getData();
                byte[] bitmap = data.getByteArray("bitmap");
                //String tag = data.getString("tag");
                CircleImageView view = (CircleImageView) msg.obj;
                GlideLoadUtils.getInstance().glideLoad(context,bitmap,view);
               /* GlideApp.with(context)
                        .load(bitmap)
                        *//*.placeholder(R.drawable.ic1)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)*//*
                        .into(view);*/
            }
        }
    };

    public void setItemClick(ItemClick itemClick) {
        this.itemClick = itemClick;
    }

    public MoCardAdapter(Context context, List<FristMetBean.PageBean.ListBean> list) {
        this.context = context;
        this.list = list;
    }

    public List<FristMetBean.PageBean.ListBean> getList() {
        return list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_mo, parent, false);
        holder = new MoCardViewHolder(view);
        return holder;
    }
    @Override
    public long getItemId(int position) {
        return position-1;
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MoCardViewHolder moCardViewHolder = (MoCardViewHolder) holder;
        if (list != null && list.size() != 0) {
            FristMetBean.PageBean.ListBean listBean = list.get(position);
            //setImage(listBean.getAvatarUrl(), (moCardViewHolder.imageIcon));
            if (!listBean.getAvatarUrl().equals(moCardViewHolder.imageIcon.getTag(R.id.image_icon))) {
                // 加载图片
                moCardViewHolder.imageIcon.setTag(R.id.image_icon, listBean.getAvatarUrl());
                GlideLoadUtils.getInstance().glideLoad(context,OssConfig.OSS_HTTP+listBean.getAvatarUrl(),
                        moCardViewHolder.imageIcon);
                //setImage(listBean.getAvatarUrl(), moCardViewHolder.imageIcon);
            }
            if (listBean.getVType()== 1) {//判断是vip等级 0非会员 1月会员 2年会员
                moCardViewHolder.imageVip.setVisibility(View.VISIBLE);
                moCardViewHolder.imageVip.setImageResource(R.mipmap.vip_month);
                moCardViewHolder.tvNikeName.setTextColor(context.getResources().getColor(R.color.colorFF3B5E));
            } else if (listBean.getVType()==2 ) {
                moCardViewHolder.imageVip.setVisibility(View.VISIBLE);
                moCardViewHolder.imageVip.setImageResource(R.mipmap.vip_year);
                moCardViewHolder.tvNikeName.setTextColor(context.getResources().getColor(R.color.colorFF3B5E));
            } else {
                moCardViewHolder.imageVip.setVisibility(View.GONE);
                moCardViewHolder.tvNikeName.setTextColor(context.getResources().getColor(R.color.color333333));
            }
            if (listBean.getGender() == 1) {//性别  1男2女
                moCardViewHolder.linearSetAge.setBackgroundResource(R.mipmap.sex_blue);
                moCardViewHolder.imageSex.setImageResource(R.mipmap.boy);
            } else {
                moCardViewHolder.linearSetAge.setBackgroundResource(R.mipmap.sex_red);
                moCardViewHolder.imageSex.setImageResource(R.mipmap.girl);
            }
           // Log.i(TAG, "onBindViewHolder: ---getBirthday-"+listBean.getBirthday());
           // Log.i(TAG, "onBindViewHolder: ---age---"+listBean.getBirthday()+"--getUserId--"+listBean.getUserId());
            if (!TextUtils.isEmpty(listBean.getBirthday())) {
                moCardViewHolder.tvAge.setText(Utils.getAge(listBean.getBirthday()));
            }
            moCardViewHolder.tvNikeName.setText(listBean.getNickName());
            moCardViewHolder.tvAddress.setText(listBean.getAscription());
            if(!TextUtils.isEmpty(listBean.getVoiceInfo())){
                moCardViewHolder.imagePlay.setVisibility(View.VISIBLE);
                if(!MediaUtil.getInstance().getPlayer().isPlaying()){
                    moCardViewHolder.imagePlay.setImageResource(R.mipmap.firstmet_open);
                }
            }else {
                moCardViewHolder.imagePlay.setVisibility(View.GONE);
            }
            if (listBean.getType() ==2) {//判断是否是主播
                moCardViewHolder.imageAnchor.setVisibility(View.VISIBLE);
            } else {
                moCardViewHolder.imageAnchor.setVisibility(View.GONE);
            }

        }
        moCardViewHolder.imageLike.setOnClickListener(this);
        moCardViewHolder.imageCall.setOnClickListener(this);
        moCardViewHolder.imagePlay.setOnClickListener(this);
        moCardViewHolder.imageUnlike.setOnClickListener(this);
        this.position = position;
    }

    /**
     * @return
     * @method
     * @description 获取头像
     * @date: 2018/10/19 17:21
     * @author: ljp
     */
    private void setImage(String url, View view) {
        //Log.i(TAG, "setImage: --------"+url);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).fileDownload(url, new OssClient.OnDownloadFile() {
                    @Override
                    public void onDownFileSuccess(InputStream inputStream) {
                        //Log.i(TAG, "onDownFileSuccess: ----------"+inputStream);
                        byte[] bitmap = null;
                        try {
                            bitmap = OssConfig.readInputStreamToByte(inputStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //if(view.getTag() != null && view.getTag().equals(url)) {
                        Message message = Message.obtain();
                        message.what = 1;
                        message.obj = view;
                        Bundle bundle = new Bundle();
                        //bundle.putString("tag",url);
                        bundle.putByteArray("bitmap", bitmap);
                        message.setData(bundle);
                        handler.sendMessage(message);
                        //  }
                    }

                    @Override
                    public void onDownFileProgress(String progress) {

                    }
                });
            }
        }).start();

    }
    @Override
    public int getItemCount() {
        return list.size();
    }

    public MoCardViewHolder getHolder() {
        return holder;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_play:
                itemClick.setItemClickPosition(v, position);
                break;
            case R.id.image_unlike:
                itemClick.setItemClickPosition(v, position);
                break;
            case R.id.image_call:
                itemClick.setItemClickPosition(v, position);
                break;
            case R.id.image_like:
                itemClick.setItemClickPosition(v, position);
                break;
        }

    }

    public class MoCardViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.image_icon)
        CircleImageView imageIcon;
        @BindView(R.id.image_play)
        ImageView imagePlay;
        @BindView(R.id.tv_nike_name)
        TextView tvNikeName;
        @BindView(R.id.image_sex)
        ImageView imageSex;
        @BindView(R.id.tv_age)
        TextView tvAge;
        @BindView(R.id.image_vip)
        ImageView imageVip;
        @BindView(R.id.tv_address)
        TextView tvAddress;
        @BindView(R.id.image_unlike)
        ImageView imageUnlike;
        @BindView(R.id.image_call)
        ImageView imageCall;
        @BindView(R.id.image_like)
        ImageView imageLike;
        @BindView(R.id.image_anchor)
        ImageView imageAnchor;
        @BindView(R.id.linear_set_age)
        LinearLayout linearSetAge;

        public MoCardViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }


    }


    public int dp(int dp) {
        final float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density);
    }

    /**
     * 获取最近距离
     *
     * @param lon 经度
     * @param lat 纬度
     * @return
     */
    public String getDistance(String lon, String lat) {
        DecimalFormat df = new DecimalFormat("0.00");//保留2位小数
       /* String str = df.format(Utils.getDistance_mo(Double.parseDouble(SPUtils.getEditoString("latitude")),
                Double.parseDouble(lat),
                Double.parseDouble(SPUtils.getEditoString("longitude")),
                Double.parseDouble(lon)));*/
       /* Log.d("Linfo", "getDistance:  my_lat:" + Double.parseDouble(SPUtils.getEditoString("latitude")) + ", my_long:"
                + Double.parseDouble(SPUtils.getEditoString("longitude")) + ", lat_" + lat + ", long_" + lon);*/
        // return str + "km";
        return null;
    }

    public interface ItemClick {
        void setItemClickPosition(View view, int position);
    }


}
